#!/bin/bash
set -e

# 脚本所在的目录
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"

# 构建目录
BUILD_DIR="${SCRIPT_DIR}/build"

echo "构建目录: ${BUILD_DIR}"

# 创建构建目录
mkdir -p "${BUILD_DIR}"

# 清理构建目录
echo "清理构建目录..."
rm -rf "${BUILD_DIR:?}"/* # 使用 :? 防止意外删除根目录等

# 进入构建目录
cd "${BUILD_DIR}"

# 检查GmSSL库是否存在
GMSSL_PATHS=("/usr/local/lib/libgmssl.so" "/usr/lib/libgmssl.so" "/usr/lib/x86_64-linux-gnu/libgmssl.so")
GMSSL_FOUND=0

for path in "${GMSSL_PATHS[@]}"; do
  if [ -f "$path" ]; then
    echo "找到GmSSL库: $path"
    GMSSL_FOUND=1
    break
  fi
done

if [ $GMSSL_FOUND -eq 0 ]; then
  echo "错误: 未找到GmSSL库。请确保GmSSL已安装在系统中。"
  echo "您可以通过以下命令安装GmSSL:"
  echo "  git clone https://github.com/guanzhi/GmSSL.git"
  echo "  cd GmSSL"
  echo "  mkdir build"
  echo "  cd build"
  echo "  cmake .."
  echo "  make"
  echo "  sudo make install"
  exit 1
fi

# 检查GmSSL头文件是否存在
GMSSL_HEADER_PATHS=("/usr/local/include/gmssl" "/usr/include/gmssl")
GMSSL_HEADER_FOUND=0

for path in "${GMSSL_HEADER_PATHS[@]}"; do
  if [ -d "$path" ]; then
    echo "找到GmSSL头文件: $path"
    GMSSL_HEADER_FOUND=1
    break
  fi
done

if [ $GMSSL_HEADER_FOUND -eq 0 ]; then
  echo "错误: 未找到GmSSL头文件。请确保GmSSL开发包已安装。"
  exit 1
fi

# 继续构建过程
echo "配置CMake项目..."
cmake ..

echo "编译项目..."
make -j$(nproc)

if [ $? -eq 0 ]; then
    echo "编译成功。"
    echo "正在运行测试..."
    make test
else
    echo "编译失败，请检查错误信息。"
    exit 1 # 编译失败时退出
fi

echo "构建过程完成。" 
cd "${SCRIPT_DIR}" # 返回项目根目录 